package top.oylan.manager.controller.admin;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.oylan.manager.entity.*;
import top.oylan.manager.service.CategoryService;
import top.oylan.manager.service.ProductService;
import top.oylan.manager.service.SectionService;
import top.oylan.manager.tools.*;
import top.oylan.manager.tools.enums.Types;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-03-31
 */
@Controller
@RequestMapping("/admin/video")
public class AdminVideoController {

    @Resource
    CategoryService categoryService;

    @Resource
    ProductService productService;

    @Resource
    FileUploader fileUploader;

    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;

    @RequestMapping(value = {"/list","","/"})
    public String index(ModelMap modelMap,@RequestParam(value = "page",defaultValue = "1")Integer page){

        Pager pager = new Pager<>();
        pager.setCurrentPage(page);
        Product product = new Product();
//        product.setStatus((byte)1);
        product.setScope((byte)4);
        pager.setCondition(product);

        List<Video> list = productService.selectVideoByPager(pager);

        pager.setList(list);
        modelMap.addAttribute("pager",pager);

        return "admin/video/list";
    }


    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(ModelMap modelMap){

        List<Category> categories = categoryService.selectCategoriesForProduct(Types.FILM);
        modelMap.addAttribute("categories",categories);
        return "admin/video/add";
    }


    /**
     * 前往编辑
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public String edit(ModelMap modelMap, @RequestParam("id")Integer id) {
        modelMap.addAttribute("categories",categoryService.selectCategoriesForProduct(Types.FILM));
        modelMap.addAttribute("video", productService.selectProductById(id));
        return "admin/video/edit";
    }


    @RequestMapping("/save")
    @ResponseBody
    public Result save(@RequestBody Product video){
        Result result = new Result();
        result.setCode((byte) 0);
        result.setMessage("保存失败");
        if(video.getId() == 0){
            // 添加
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            video.setAuthorId(user.getId().shortValue());
            video.setCreateTime(new Date());
            video.setType(video.getType());
            productService.addProduct(video);
            Map<String,Object> data = new HashMap<>();
            data.put("id",video.getId());
            result.setData(data);
            result.setMessage("添加成功");
            result.setCode((byte)1);
        } else{
            // 编辑
            productService.updateProduct(video);
            result.setMessage("修改成功");
            result.setCode((byte)1);
        }
        return result;
    }


    @Resource
    SectionService sectionService;

    @RequestMapping(value = "/sections")
    public String sections(@RequestParam int productId,ModelMap modelMap){
        modelMap.addAttribute("productId",productId);
        Section section = new Section();
        section.setProductId(productId);
        section.setParentId(0);
        List<Section> list = sectionService.selectSectionsByCondition(section);
        modelMap.addAttribute("list",list);
        return "admin/video/sections";
    }

    @RequestMapping("/section/add")
    public String addSection(ModelMap modelMap,@RequestParam Integer productId){
        Course course = productService.selectProductById(productId);
        modelMap.addAttribute("video",course);
        return "admin/video/addSection";
    }

    @RequestMapping(value = "/section/save",method = RequestMethod.POST)
    @ResponseBody
    public Result saveSection(@RequestBody JSONObject jsonObject){

        Result result = new Result();
        int scope = jsonObject.getIntValue("scope");
        int id =  sectionService.saveSectionFromJSON(jsonObject);
        if(id > 0){
            if(scope == 2){
                sectionService.saveVideos(jsonObject,-1);
            } else if(scope == 3){
                sectionService.saveVideos(jsonObject,id);
            }
        }
        result.setCode((byte) 1);
        return result;
    }

    @RequestMapping(value = "/section/edit",method = RequestMethod.GET)
    public String editSection(ModelMap modelMap,
            @RequestParam (value = "id",defaultValue = "0",required = false) Integer id,
            @RequestParam (value = "productId",defaultValue = "0",required = false)Integer productId){

        Section section = new Section();
        List<Section> videos;
        Product product;
        if(productId != null && productId > 0){
            product = productService.selectProductById(productId);
            section.setLv((byte)2);
            section.setProductId(productId);
            section.setParentId(-1);
            videos = sectionService.selectSectionsByCondition(section);
            section.setTitle(product.getTitle());
            section.setDescription(product.getDescription());
            section.setId(0);
        }else{
            section = sectionService.findSectionById(id);
            product = productService.selectProductById(section.getProductId());
            Section condition = new Section();
            condition.setParentId(section.getId());
            condition.setProductId(product.getId());
            videos = sectionService.selectSectionsByCondition(condition);
        }
        modelMap.addAttribute("videos",videos);
        modelMap.addAttribute("section",section);
        modelMap.addAttribute("product",product);
        return "admin/video/editSection";
    }


    @RequestMapping(value = "section/update",method = RequestMethod.POST)
    @ResponseBody
    public Result sectionUpdate(@RequestBody JSONObject object){
        Result result = new Result();
        int scope = object.getIntValue("scope");
        int id = object.getIntValue("id");
        if(scope == 3 && id > 0){
            // 多部
            Section section = new Section();
            section.setId(id);
            section.setStatus(object.getByte("status"));
            section.setTitle(object.getString("title"));
            section.setDescription(object.getString("description"));
            sectionService.update(section);
            jmsMessagingTemplate.convertAndSend("queue.update_section_video",object.toJSONString());
            result.setCode((byte) 1);
        }else if(scope == 2 && id == 0){
            // 多集
            object.put("id",-1);
            jmsMessagingTemplate.convertAndSend("queue.update_section_video",object.toJSONString());
            result.setCode((byte) 1);
        }else{
            result.setMessage("参数有误");
        }
        return result;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file){
        JSONObject object = new JSONObject();
        Result result = fileUploader.upload(file, Directory.ART);
        if(result.getCode() == 1){
            object.put("status",1);
            object.put("path",result.getData().get("path").toString());
        }else{
            object.put("status",0);
        }
        return object;
    }

    @RequestMapping(value = "/file/remove",method = RequestMethod.GET)
    public Result unlink(@RequestParam(value = "path")String path){

        Result result = new Result((byte) 1,"成功");
        fileUploader.removeFile(SystemConstants.UPLOAD_ROOT_PATH+path);
        return result;
    }

    @Autowired
    QiniuTools qiniuTools;

    @RequestMapping(value = "/file/delete",method = RequestMethod.GET)
    @ResponseBody
    public Result remove(@RequestParam(value = "name")String name){
        Result result = new Result((byte) 1,"成功");
        qiniuTools.delete(name);
        return result;
    }
}
